package coolq.yaozhenyong.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.BeanUtils;

import com.forte.qqrobot.BaseConfiguration;
import com.forte.qqrobot.anno.Filter;
import com.forte.qqrobot.anno.Listen;
import com.forte.qqrobot.anno.depend.Beans;
import com.forte.qqrobot.beans.cqcode.CQCode;
import com.forte.qqrobot.beans.messages.msgget.GroupMsg;
import com.forte.qqrobot.beans.messages.result.GroupMemberInfo;
import com.forte.qqrobot.beans.messages.types.MsgGetTypes;
import com.forte.qqrobot.beans.types.CQCodeTypes;
import com.forte.qqrobot.sender.MsgSender;
import com.forte.qqrobot.utils.CQCodeUtil;

import coolq.yaozhenyong.Impl.ApiCocportImpl;
import coolq.yaozhenyong.Impl.OpenLayoutImpl;
import coolq.yaozhenyong.bean.ApiCocport;
import coolq.yaozhenyong.bean.Apiport;
import coolq.yaozhenyong.bean.Claninform;
import coolq.yaozhenyong.bean.ClansClan;
import coolq.yaozhenyong.bean.CocGroupUser;
import coolq.yaozhenyong.bean.CocQq;
import coolq.yaozhenyong.bean.CocQqRemove;
import coolq.yaozhenyong.bean.GradeAdmin;
import coolq.yaozhenyong.bean.GradeAdministrator;
import coolq.yaozhenyong.bean.Lexicon;
import coolq.yaozhenyong.bean.LexiconIllegal;
import coolq.yaozhenyong.bean.OpenLayout;
import coolq.yaozhenyong.bean.Spam;
import coolq.yaozhenyong.bean.SpamAdmin;
import coolq.yaozhenyong.bean.SysUser;
import coolq.yaozhenyong.cocApi.custom.ClansPlayersTagCustom;
import coolq.yaozhenyong.cocApi.entity.ClansPlayersTag.ClansPlayersTag;
import coolq.yaozhenyong.cocApi.entity.ClansPlayersTag.Heroes;
import coolq.yaozhenyong.custom.CocCustom;
import coolq.yaozhenyong.custom.DlCustom;
//import coolq.yaozhenyong.custom.CocCustomImage;
import coolq.yaozhenyong.custom.GroupHtmlAndQqService;
import coolq.yaozhenyong.custom.QqCqcustom;
import coolq.yaozhenyong.custom.SpringContextUtil;
import coolq.yaozhenyong.custom.TimeUtils;
import coolq.yaozhenyong.custom.entity.ems.Ems;
import coolq.yaozhenyong.custom.entity.ems.Remark;
import coolq.yaozhenyong.mapper.LexiconMapper;
import coolq.yaozhenyong.service.ApiportService;
import coolq.yaozhenyong.service.ClaninformService;
import coolq.yaozhenyong.service.ClansClanService;
import coolq.yaozhenyong.service.CocGroupUserService;
import coolq.yaozhenyong.service.CocQqRemoveService;
import coolq.yaozhenyong.service.CocQqService;
import coolq.yaozhenyong.service.GradeAdminService;
import coolq.yaozhenyong.service.GradeAdministratorService;
import coolq.yaozhenyong.service.GroupListService;
import coolq.yaozhenyong.service.LexiconIllegalService;
import coolq.yaozhenyong.service.LexiconService;
import coolq.yaozhenyong.service.SpamAdminService;
import coolq.yaozhenyong.service.SpamService;
import coolq.yaozhenyong.service.SysUserService;
@Beans
public class QQGroupRecordController {
	
	public GradeAdminService gService = SpringContextUtil.getBean(GradeAdminService.class);
	public LexiconService lservice = SpringContextUtil.getBean(LexiconService.class);
	public LexiconIllegalService iservice = SpringContextUtil.getBean(LexiconIllegalService.class);
	public GradeAdministratorService gradeservice = SpringContextUtil.getBean(GradeAdministratorService.class);
	public SpamService spanservice = SpringContextUtil.getBean(SpamService.class);
	public SpamAdminService adminservice = SpringContextUtil.getBean(SpamAdminService.class);
	public GroupListService grouplistservice = SpringContextUtil.getBean(GroupListService.class);
	public LexiconMapper lsmapper = SpringContextUtil.getBean(LexiconMapper.class);
	private OpenLayoutImpl openlayout = SpringContextUtil.getBean(OpenLayoutImpl.class);
	public CocGroupUserService CocService = SpringContextUtil.getBean(CocGroupUserService.class);
	/***
	 * 一.实现QQ语言库回复功能
	 * 
	 * 二.实现违禁词库的撤回功能
	 * @param msg
	 * @param msgsender
	 */
	@Listen(MsgGetTypes.groupMsg)
	@Filter	
	public void grouprecords(GroupMsg msg,CQCodeUtil cqCodeUtil,MsgSender msgsender) {
			String msg2 = msg.getMsg();
			String m = msg.getMsg();
			if(msg.getQQ().equals("2854196310")||msg.getQQ().equals("2854196312")||msg.getQQ().equals("2854196306")||msg.getMsg().indexOf("qq点歌")!=-1||msg.getMsg().indexOf("网易点歌")!=-1) {
				return ;
			}
			if(("822628363".equals(msg.getQQ())||"2058308326".equals(msg.getQQ()))&&!"893778789".equals(msg.getGroup())) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQCode())+" 好巧哦，天使你也在，这个群就交给我了，你去更需要帮助的群把！");
			}
			
			/** 判断这个群机器人是否为开启状态 **/
			GradeAdmin gradeadmin = gService.query().eq("gradenumber", msg.getGroup()).eq("codes", "robot").eq("isgoto", "1").one();
			if(gradeadmin!=null) {
				if(cqCodeUtil.isAt(msg2, BaseConfiguration.getLocalQQCode())) {
					m = cqCodeUtil.removeCQCodeFromMsg(m, CQCodeTypes.at);
					m = m.replaceAll(" ", "").replaceAll("	", "").replaceAll(",", "").replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", "").replaceAll("＃", "#");
					// 查询鱼情
					if("部落鱼情".equals(m)||"coc鱼情".equals(m)||"查询鱼情".equals(m)||"查询部落鱼情".equals(m)||"查询coc鱼情".equals(m)||"玩家状态".equals(m)||"全球玩家状态".equals(m)) {
						ApiportService service = SpringContextUtil.getBean(ApiportService.class);
						Apiport ones = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
						if(ones!=null) {
							yuqing(cqCodeUtil,msgsender,msg);
							return ;
						}
					}
					if(m.length()>0) {
						if(m.length()>4&&(m.indexOf("绑定")!=-1||m.indexOf("#")!=-1||m.indexOf("＃")!=-1||m.indexOf("查询")!=-1||m.indexOf("部落")!=-1||m.indexOf("村庄")!=-1)) {
							/** 绑定部落 **/
							try {
								Boolean cocbangding = cocbangding(msg,cqCodeUtil,msgsender,m);
								if(cocbangding) {
									return ;
								}
							} catch (Exception e) {
								System.err.println("绑定部落报错了!时间："+TimeUtils.getStringDate());
								return ;
							}
							/** 查询村庄 **/
							try {
								Boolean coc = coc(msg,cqCodeUtil,msgsender,m);
								if(coc) {
									return ;
								}
							} catch (Exception e) {
								System.err.println("查询部落报错了!时间："+TimeUtils.getStringDate());
								return ;
							}
							/** 查询快递 **/
							try {
								Boolean ems = ems(msg,cqCodeUtil,msgsender,m);
								if(ems) {
									return ;
								}
							} catch (Exception e) {
								System.err.println("查询快递报错了!时间："+TimeUtils.getStringDate());
								return ;
							}
							/** 部落报名 **/
							try {
								boolean cocqq = cocqq(msg,cqCodeUtil,msgsender, m);
								if(cocqq) {
									return ;
								}
							} catch (Exception e) {
								e.printStackTrace();
								System.err.println("部落报名出错了!时间："+TimeUtils.getStringDate());
								return ;
							}
						}
						try {
							/** 查找对应部落 **/
							Boolean groupUser = cocGroupUser(msg,cqCodeUtil,msgsender,m);
							if(groupUser) {
								return ;
							}
						} catch (Exception e) {
							System.err.println("COC绑定查询部落报错了!时间："+TimeUtils.getStringDate());
							return ;
						}
						if(msg.getQQ().equals("936642284")) {
							//群广播功能指令
							Boolean broadcast = broadcast(msg,cqCodeUtil,msgsender);
							if(broadcast) {
								return ;
							}
						}
					}
				}
				
				
				
				//2.代管进行管理
				if(msg2.indexOf("禁言")!=-1||msg2.indexOf("踢")!=-1||msg2.indexOf("拉黑")!=-1) {
					Boolean administrator =  gradeAdministrotor(msg,cqCodeUtil,msgsender);
					if(administrator) {
						grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
						return ;
					}
				}
				//部落阵型
				if(msg2.indexOf("阵型")!=-1) {
					String opmsg = msg.getMsg();
					if(cqCodeUtil.isAt(opmsg, BaseConfiguration.getLocalQQCode())) {
						opmsg  = cqCodeUtil.removeCQCodeFromMsg(opmsg, CQCodeTypes.at);
						opmsg = opmsg.replace(" ", "");
					}
					boolean openLayout2 = openLayout(opmsg,msg,msgsender,cqCodeUtil);
					if(openLayout2) {
						grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
						return ;
					}
				}
				//3.刷屏禁言
				Boolean spam = spam(msg,msgsender,cqCodeUtil);
				if(spam) {
					grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
					return ;
				}
				//4.违禁词处理
				Boolean lexiconIllegal = LexiconIllegal(msg,msgsender);
				if(lexiconIllegal) {
					grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
					return ;
				}
				//1.机器人应答功能
				Boolean lexicon = lexicon(msg,cqCodeUtil,msgsender);
				if(lexicon) {
					return ;
				}
				if(cqCodeUtil.isAt(msg2, BaseConfiguration.getLocalQQCode())) {
					QQGroupAtController.tuling(msg,cqCodeUtil,msgsender,m);
				}
			}
		
	}
	/***
	 * 群广播开关
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @return
	 */
	private Boolean broadcast(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender) {
		String[] split = msg.getMsg().split(" ");
		if(split.length == 4&&"群广播".equals(split[1])) {
			try {
				GroupListService group = SpringContextUtil.getBean(GroupListService.class);
				if(split[3].equals("开启")||split[3].equals("关闭")) {
					boolean update = group.update().eq("groupcode", split[2]).set("borad", split[3].equals("开启")?2:1).update();
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), update+"群"+split[2]+"的群广播功能 "+split[3]);
				}else {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), "格式为@我 群广播 群号 开启/关闭");
				}
				return true;
			} catch (Exception e) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), "报错，格式为@我 群广播 群号 开启/关闭");
				return true;
			}
		}
		return false;
	}
	/****
	 * 查找绑定对应的
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 * @return
	 */
	private Boolean cocGroupUser(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		CocGroupUser one = CocService.query().eq("groupnumber", msg.getGroup()).eq("msg", m).one();
		if(one!=null) {
			String groupmsg = cqCodeUtil.getCQCode_At(msg.getQQ()) +" ";
			ApiportService service = SpringContextUtil.getBean(ApiportService.class);
			Apiport ones = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
			if(ones!=null) {
				ApiCocportImpl apicoc = SpringContextUtil.getBean(ApiCocportImpl.class);
				ApiCocport Cocport = apicoc.query().eq("uuid", ones.getAppkey()).one();
				if(Cocport!=null&&Cocport.getResidue()>0) {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 正在连接网络查询"+one.getType()+"【#"+ one.getCoctag()+"】的相关信息！请耐心等待。。。");
					CocCustom.goCocUrl(one.getType(), one.getCoctag(), msg, cqCodeUtil, msgsender);
					ones.setSum(ones.getSum()+1);
					Cocport.setResidue(Cocport.getResidue()-1);
					apicoc.updateById(Cocport);
					service.updateById(ones);
					return true;
				}else {
					groupmsg +="本群今日使用次数已达上限，心疼一下服务器吧；\n他太累了，让他休息一下！";
				}
			}else {
				groupmsg +="本群还未开通此功能！";
			}
			msgsender.SENDER.sendGroupMsg(msg.getGroup(),groupmsg);
			return true;
		}
		return false;
	}
	/**
	 * coc 部落战 联赛报名
	 * @param msg
	 * @param cqCodeUtil
	 * @param m
	 * @return
	 */
	private boolean cocqq(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		String[] split = m.split("#");
		if(split.length==3&&"退出".equals(split[2])) {
			ClaninformService clanservice = SpringContextUtil.getBean(ClaninformService.class);
			Claninform clan = clanservice.query().eq("qunnumber", msg.getGroup()).eq("kenning", split[0]).eq("isgoto", "1").one();
			
			ClansClanService clansclanservice = SpringContextUtil.getBean(ClansClanService.class);
			ClansClan clansclan = clansclanservice.query().eq("id", clan.getClansclanId()).one();
			
			CocQqService cocqqservice = SpringContextUtil.getBean(CocQqService.class);
			String upperCase = split[1].toUpperCase();
			try {
				CocQq cocqq = cocqqservice.query().eq("uuid", clansclan.getUuid()).eq("tag", "#"+upperCase).eq("qunnumber", msg.getGroup()).one();
				if(cocqq!=null) {
					CocQqRemoveService cocremoveservice = SpringContextUtil.getBean(CocQqRemoveService.class);
					CocQqRemove remove = new CocQqRemove();
					//判断是否是同一个人绑定的！
					if(cocqq.getQqnumber().equals(msg.getQQ())) {
						
						BeanUtils.copyProperties(cocqq, remove,"id");
						
						cocqqservice.removeById(cocqq);
						remove.setRemoveqqnumber(msg.getQQ());
						cocremoveservice.save(remove);
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 您的村庄【"+cocqq.getTagname()+"】已成功退出本次【"+clansclan.getName()+"】的"+clan.getType()+"的报名。");
					}else{
						GradeAdministrator one = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("cocgoto", "1").one();
						if(one!=null) {
							BeanUtils.copyProperties(cocqq, remove,"id");
							cocqqservice.removeById(cocqq);
							remove.setRemoveqqnumber(msg.getQQ());
							cocremoveservice.save(remove);
							msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 你已取消"+cqCodeUtil.getCQCode_At(cocqq.getQqnumber())+" 【"+cocqq.getTagname()+"】在【"+clansclan.getName()+"】部落"+clan.getType()+"的报名。");
							return true;
						}
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 除了本人和代管以外，其他人不可以取消别人的报名！");
						return true;
					}
					return true;
				}else {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 未查到#"+upperCase+"的报名情况！");
					return true;
				}
			} catch (Exception e) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 取消失败，请找本群的机器人管理员去后台删除");
			}
			
			
		}else if(split.length==2&&split[1].equals("报名情况")) {
			ClaninformService clanservice = SpringContextUtil.getBean(ClaninformService.class);
			Claninform clan = clanservice.query().eq("qunnumber", msg.getGroup()).eq("kenning", split[0]).eq("isgoto", "1").one();
			
			ClansClanService clansclanservice = SpringContextUtil.getBean(ClansClanService.class);
			ClansClan clansclan = clansclanservice.query().eq("id", clan.getClansclanId()).one();
			
			CocQqService cocqqservice = SpringContextUtil.getBean(CocQqService.class);
			List<CocQq> list = cocqqservice.query().eq("uuid", clansclan.getUuid()).eq("qunnumber", msg.getGroup()).orderBy(true, false, "CAST(versus_battle_win_count as SIGNED)").list();
			
			msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+""
					+ "\n● "+clansclan.getName()
					+ "\n● 报名人数："+list.size()+"\n● 报名名单已私聊 \n● 报名情况（网站）：http://yzycoc.com/qq/cocApi/apply?tag="+clansclan.getUuid());
			String reply ="报名名单（简略）";
			for (CocQq cocQq : list) {
				String re = "";
				if(cocQq.getTownHallWeaponLevel()!=null) {
					re ="(" +cocQq.getTownHallWeaponLevel()+"[CQ:emoji,id=11088])";
				}
				reply += "\n\n● 名称:"+cocQq.getTagname()
						+ "\n● 标签:"+cocQq.getTag()
						+ "\n● 大本:"+cocQq.getTownHallLevel()+re
						+ "\n● 蛮王"+cocQq.getBarbarianKing()+" 女皇"+cocQq.getArcherQueen()+" 咏王"+cocQq.getGrandWarden()
						+ "\n● 匹配值"+cocQq.getVersusBattleWinCount();
			}
			msgsender.SENDER.sendPrivateMsg(msg.getQQ(), reply+"\n\n● 报名情况（网站）：http://yzycoc.com/qq/cocApi/apply?tag="+clansclan.getUuid());
			return true;
		}else if(split.length>1) {
			ClaninformService clanservice = SpringContextUtil.getBean(ClaninformService.class);
			Claninform clan = clanservice.query().eq("qunnumber", msg.getGroup()).eq("kenning", split[0]).eq("isgoto", "1").one();
			//是否存在这个联赛报名
			try {
				if(clan!=null) {//存在
					//查询玩家是否存在
					msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 正在连接网络查询【#"+ split[1]+"】的村庄信息！请等待...");
					ClansPlayersTag findAll = ClansPlayersTagCustom.findAll(split[1]);
					if(findAll!=null&&findAll.getDataisnull()) {
						ClansClanService clansclanservice = SpringContextUtil.getBean(ClansClanService.class);
						ClansClan clansclan = clansclanservice.query().eq("id", clan.getClansclanId()).one();
						CocQqService cocqqservice = SpringContextUtil.getBean(CocQqService.class);
						CocQq cocqq = cocqqservice.query().eq("uuid", clansclan.getUuid()).eq("tag", findAll.getTag()).eq("qunnumber", msg.getGroup()).one();
						if(cocqq!=null) {//存在这个用户，更新数据
							//查询如果此用户已报名，防止用户二次报名
							List<Heroes> heroes = findAll.getHeroes();
							if(heroes!=null) {
								for (Heroes h : heroes) {
									if("Barbarian King".equals(h.getName())) {
										cocqq.setBarbarianKing(h.getLevel());
										continue;
									}
									if("Archer Queen".equals(h.getName())) {
										cocqq.setArcherQueen(h.getLevel());
										continue;
									}
									if("Grand Warden".equals(h.getName())) {
										cocqq.setGrandWarden(h.getLevel());
										continue;
									}
								}
							}
							cocqq.setTownHallLevel(findAll.getTownHallLevel());
							if(findAll.getTownHallWeaponLevel()!=null) {
								cocqq.setTownHallWeaponLevel(findAll.getTownHallWeaponLevel());
							}
							String clantag = findAll.getClan()==null?"":findAll.getClan().getTag();
							if(clantag.equals(clansclan.getTag())) {
								cocqq.setIsgoto(true);
							}else {
								cocqq.setIsgoto(false);
							}
							cocqq.setVersusBattleWinCount(findAll.getVersusBattleWinCount());
							if(split.length==3) {
								String remark = cocqq.getRemark()==null?"":cocqq.getRemark();
								String sp =split[2]==null?"":split[2];
								if(!sp.equals(remark)) {
									cocqqservice.updateById(cocqq);
									cocqq.setRemark(split[2]);
									msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ()) + " 已更新备注!");
									return true;
								}
							}
							cocqqservice.updateById(cocqq);
							String reply = cqCodeUtil.getCQCode_At(msg.getQQ())+" "
									+ "玩家【"+findAll.getName()+"】"+findAll.getTag()+"已经参与了本次"+clan.getType()+"报名，请不要重复报名！\n"
									+ "报名人"+cocqq.getQqnumber()+"  报名时间\n"+cocqq.getCreateDate()+"\n如需取消本次报名：\n@我 "+clan.getKenning()+"#标签#退出";
							msgsender.SENDER.sendGroupMsg(msg.getGroup(), reply);
							return true;
						}else {//不存在这个用户，完全重新报名
							cocqq = new CocQq();
							//保存
							try {
								GroupMemberInfo groupMemberInfo = msgsender.GETTER.getGroupMemberInfo(msg.getGroup(),msg.getQQ());
								cocqq.setQqimageurl(groupMemberInfo.getHeadImgUrl());
								String card = groupMemberInfo.getCard();
								if(card==null||card==""||card.length()<1) {
									card = groupMemberInfo.getName();
								}
								cocqq.setName(card);
							} catch (Exception e) {
							}
							cocqq.setUuid(clansclan.getUuid());
							cocqq.setQunnumber(msg.getGroup());
							cocqq.setQqnumber(msg.getQQ());
							cocqq.setTag(findAll.getTag());
							cocqq.setTagname(findAll.getName());
							cocqq.setTownHallLevel(findAll.getTownHallLevel());
							if(findAll.getTownHallWeaponLevel()!=null) {
								cocqq.setTownHallWeaponLevel(findAll.getTownHallWeaponLevel());
							}
							
							cocqq.setExpLevel(findAll.getExpLevel());
							cocqq.setTrophies(findAll.getTrophies());
							cocqq.setWarStars(findAll.getWarStars());
							cocqq.setAttackWins(findAll.getAttackWins());
							cocqq.setDefenseWins(findAll.getDefenseWins());
							cocqq.setVersusBattleWinCount(findAll.getVersusBattleWinCount());
							String league =findAll.getLeague()==null?"":findAll.getLeague().getIconUrls()==null?"":findAll.getLeague().getIconUrls().getSmall();
							cocqq.setLeague(league);
							cocqq.setCreateDate(TimeUtils.getStringDate());
							List<Heroes> heroes = findAll.getHeroes();
							if(heroes!=null) {
								for (Heroes h : heroes) {
									if("Barbarian King".equals(h.getName())) {
										cocqq.setBarbarianKing(h.getLevel());
										continue;
									}
									if("Archer Queen".equals(h.getName())) {
										cocqq.setArcherQueen(h.getLevel());
										continue;
									}
									if("Grand Warden".equals(h.getName())) {
										cocqq.setGrandWarden(h.getLevel());
										continue;
									}
								}
							}
							String clantag = findAll.getClan()==null?"":findAll.getClan().getTag();
							
							String reply = " 【"+findAll.getName()+"】"+findAll.getTag()+"您已成功报名【"+clansclan.getName()+"】部落的部落战！";
							if(clantag.equals(clansclan.getTag())) {
								cocqq.setIsgoto(true);
							}else {
								cocqq.setIsgoto(false);
								reply =reply + "\n您现在还不在部落内，请尽早回归部落方便开战！";
							}
							cocqq.setRemoves(true);
							if(split.length==3) {
								cocqq.setRemark(split[2]);
							}
							//保存前在确定一下这个用户是否报名过
							CocQq cocqq2 = cocqqservice.query().eq("uuid", clansclan.getUuid()).eq("tag", findAll.getTag()).eq("qunnumber", msg.getGroup()).one();
							if(cocqq2==null) {
								cocqqservice.save(cocqq);
								msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+reply);
							}else {
								String replys = cqCodeUtil.getCQCode_At(msg.getQQ())+" "
										+ "玩家【"+findAll.getName()+"】"+findAll.getTag()+"已经参与了本次"+clan.getType()+"报名，请不要重复报名！\n"
										+ "报名人"+cocqq.getQqnumber()+"  报名时间\n"+cocqq.getCreateDate()+"\n如需取消本次报名：\n@我 "+clan.getKenning()+"#标签#退出";
								msgsender.SENDER.sendGroupMsg(msg.getGroup(), replys);
							}
						}
					}else {
						//无法查找到玩家信息
						String replyto = findAll==null?"未知！":findAll.getError();
						replyto = "报名失败！因为需要查询游戏信息，现无法获取，所以无法报名，请稍后重试！\n出现的问题：\n"+replyto;
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+replyto);
					}
					return true;
				}
			} catch (Exception e) {
				String  replyto = "报名失败！因为需要查询游戏信息，现无法获取，所以无法报名，请稍后重试！\n出现的问题：\n请截屏反馈给作者！";
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+replyto);
			}
			
		}
		return false;
	}
	/***
	 *	处理发送快递信息
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 * @return false未处理 true 已处理
	 */
	private Boolean ems(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		String substring = m.substring(0, 4);
		if(substring.equals("查询快递")) {
			ApiportService service = SpringContextUtil.getBean(ApiportService.class);
			Apiport one = service.query().eq("qqnumber", msg.getGroup()).eq("type","ems").eq("isgoto", "1").one();
			if(one!=null) {
				Pattern pattern = Pattern.compile("[A-Za-z0-9]");
				Matcher matcher = pattern.matcher(m);
				 if (matcher.find()) {
					 int indexOf = m.indexOf(matcher.group());
					 if(indexOf<=4) {
						 msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+"你查询快递的格式错误哦！");
						 return true;
					 }else {
						 //快递名称
						 String kuaidi = m.substring(4,indexOf);
						 String substring2 = m.substring(indexOf,m.length());
						 String ems = QqCqcustom.ems(kuaidi);
						 if(ems==null) {
							 msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+"你查询"+kuaidi+"我不晓得哪个公司哦");
							 return true;
						 }else{
							 /** 成功使用 **/
							 one.setSum(one.getSum()+1);
							 service.updateById(one);
							 String[] emsNumber = getEmsNumber(substring2);
							 Ems emsUrl = new Ems();
							 if(emsNumber.length==1) {
								 emsUrl = QqCqcustom.toEmsUrl(one.getAppkey(),ems,emsNumber[0],"");
							 }else if(emsNumber.length==2){
								 emsUrl = QqCqcustom.toEmsUrl(one.getAppkey(),ems,emsNumber[0],emsNumber[1]);
							 }else {
								 msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+substring2+"这个我无法给你查询哦！");
								 return true;
							 }
							 String privatemsg ="";
							 if(emsUrl!=null) {
								 /*** 处理最后返回的结果集 ***/
								 String emsmsg = cqCodeUtil.getCQCode_At(msg.getQQ())+" ";
								 if(emsUrl.getResultcode().equals("200")&&emsUrl.getError_code().equals("0")) {
									 //群发
									 List<Remark> list = new ArrayList<Remark>();
									 if(emsUrl.getResult()!=null&&emsUrl.getResult().getList().size()>0) {
										 privatemsg = "您快递的详细信息：\n快递号："+emsUrl.getResult().getNo()+"\n";
										 list = emsUrl.getResult().getList();
									 }
									 if(list.size()>0) {
										 emsmsg += "您快递最新消息：\n\n"+list.get(list.size()-1).getDatetime()+"\n"+list.get(list.size()-1).getRemark()+"\n\n物流详细信息已私聊，如未收到消息，请添加我为好友哦！";
										 for (Remark remark : list) {
											 privatemsg += remark.getDatetime()+"\n"+remark.getRemark()+"\n\n";
										}
										 msgsender.SENDER.sendPrivateMsg(msg.getQQ(), privatemsg+"如果不想接收消息，你可以屏蔽我哦！");
									 }else {
										 if(emsUrl.getResult()!=null) {
											 emsmsg +=QqCqcustom.status_detail(emsUrl.getResult().getStatus_detail());
										 }else {
											 emsmsg +="无法查询此次快递！";
											 msgsender.SENDER.sendPrivateMsg("936642284", msg.getGroup()+"群的群员"+msg.getQQ()+"查询快递"+msg.getMsg()+"出现错误!"+"\n错误原因是"+emsUrl.getReason());
										 }
									 }
								 }else {
									 String rtnUrl = QqCqcustom.returnUrl(emsUrl.getResultcode(),emsUrl.getError_code());
									 emsmsg += rtnUrl;
								 }
								 
								 msgsender.SENDER.sendGroupMsg(msg.getGroup(), emsmsg);
								 return true;
							 }else {
								 msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+"恕在下能力浅薄，未能根据你的需要查找出对应的快递信息！");
								 return true;
							 }
						 }
						
					 }
				 }
			}
			return false;
		}
		return false;
	}
	private String[] getEmsNumber(String string) {
		if(string.indexOf("收")!=-1) {
			String[] a = string.split("收");
			a[1] = "&senderPhone="+a[1];
			return a;
		}else if(string.indexOf("寄")!=-1) {
			String[] a = string.split("寄");
			a[1] = "&receiverPhone="+a[1];
			return a;
		}else {
			String[] a = {string};
			return a;
		}
	}
	/****
	 * 跳转到部落查询
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 * @return
	 */
	private Boolean coc(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		String[] split = m.split("#");
		if(split.length==2) {
			String substring = split[0];
			substring = substring.replaceAll(" ", "");
			if(substring.equals("我的村庄")||substring.equals("我的部落")||substring.equals("查询部落")||substring.equals("查询村庄")||substring.equals("查询玩家")||substring.equals("查询部落配置")||substring.equals("部落配置")) {
				ApiportService service = SpringContextUtil.getBean(ApiportService.class);
				Apiport one = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
				if(one!=null) {
					ApiCocportImpl apicoc = SpringContextUtil.getBean(ApiCocportImpl.class);
					ApiCocport Cocport = apicoc.query().eq("uuid", one.getAppkey()).one();
					if(Cocport!=null&&Cocport.getResidue()>0) {
						try {
							String blpz =" 请等待";
							if(substring.equals("查询部落配置")||substring.equals("部落配置")) {
								SysUserService sysuserservice = SpringContextUtil.getBean(SysUserService.class);
								SysUser sys = sysuserservice.query().eq("username", msg.getGroup()).one();
								if(sys==null||sys.getAdministratoring()==null||sys.getAdministratoring()==false) {
									msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 本群还无法使用此功能！");
									return true;
								}
								blpz =" 查询配置需要的时间比较长，请耐心等待..."; 
							}
							msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+blpz);
							CocCustom.goCocUrl(substring,split[1],msg,cqCodeUtil,msgsender);
							one.setSum(one.getSum()+1);
							Cocport.setResidue(Cocport.getResidue()-1);
							apicoc.updateById(Cocport);
							service.updateById(one);
						} catch (Exception e) {
							e.printStackTrace();
							String goCocUrl = " 未查到你的#"+split[1]+"信息哦！";
							msgsender.SENDER.sendPrivateMsg("936642284",split[1]+"的标签好像出问题了！记住此标签，出现bug了！" );
							msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" "+ goCocUrl);
						}
						return true;
					}else {
						msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 本群今日使用次数已达上限！\n心疼一下服务器吧，他太累了，让他休息一下" );
						return true;
					}
				}else {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 本群还未启用此功能！");
				}
				return true;
			}
			
		}
		return false;
	}
	/****
	 * 绑定
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 * @return
	 */
	private Boolean cocbangding(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		String substring = m.substring(0, 4);
		if(substring.equals("绑定村庄")||substring.equals("绑定部落")) {
			ApiportService service = SpringContextUtil.getBean(ApiportService.class);
			Apiport ones = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
			if(ones==null) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+" 此群还未启用此功能哦！");
				return true;
			}
			GradeAdministrator one = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("cocgoto", "1").one();
			if(one!=null) {
				String groupmsg = cqCodeUtil.getCQCode_At(msg.getQQ())+" ";
				String[] split = m.split("#");
				if(split.length==3) {
					if(split[0].length()>0&&split[1].length()>0&&split[2].length()>1) {
						CocGroupUser one2 = CocService.query().eq("groupnumber", msg.getGroup()).eq("msg", split[2]).one();
						if(one2!=null) {
							groupmsg += "【"+split[2]+"】此代称在本群已被绑定，请换一个吧！";
						}else {
							msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+" 正在联网查询【#"+split[1]+"】"+m.substring(2,4)+"是否存在！请耐心等待。。。");
							Boolean goCocBd = QqCqcustom.goCocBd(split);
							if(goCocBd) {
								CocGroupUser cocgroupuser = new CocGroupUser(TimeUtils.getStringDate(),msg.getGroup(),msg.getQQ(),split[2],m.substring(2,4),split[1]);
								CocService.save(cocgroupuser);
								groupmsg +="绑定成功，以后【@我 "+split[2]+"】即可获取"+split[1]+"的"+m.substring(2,4)+"信息";
							}else {
								groupmsg += "【#"+split[1]+"】此标签无法查到对于"+m.substring(2,4)+"的信息,请核对后再绑定！\n\n推荐直接进游戏复制标签哦！";
							}
						}
					}else if(split[1].length()==0){
						groupmsg += "标签格式错误！";
					}else if(split[2].length()<2) {
						groupmsg +="代称的长度必须大于2位！";
					}else {
						groupmsg += "格式错误哦，正确的格式为:"+substring+"#标签#代称";
					}
				}else {
					groupmsg += "格式错误哦，正确的格式为:"+substring+"#标签#代称";
				}
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), groupmsg);
			}else {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+" 在此群你还没有权力绑定自己的coc，请联系相关代管进行绑定！");
			}
			
			return true;
		}
		return false;
	}
	/***
	 * 部落鱼情
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param msg
	 */
	private void yuqing(CQCodeUtil cqCodeUtil, MsgSender msgsender, GroupMsg msg) {
		String[] c = MyqqRobot.clashofclansforecaster;
		long datadifference = TimeUtils.datadifference(c[1]);
		if(datadifference<120&&"1".equals(c[2])) {
			msgsender.SENDER.sendGroupMsg(msg.getGroup(), c[0]);
		}else {
			String goyuqing = CocCustom.goyuqing();
			if(goyuqing==null) {
				MyqqRobot.clashofclansforecaster[2] = "0";
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), c[0] + "\n◎━"+datadifference/60+"分钟前获取━◎");
			}else {
				MyqqRobot.clashofclansforecaster[0] = goyuqing;
				MyqqRobot.clashofclansforecaster[1] = TimeUtils.getStringDate();
				MyqqRobot.clashofclansforecaster[2] = "1";
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), goyuqing);
			}
		}
	}
	private boolean openLayout(String clansmsg, GroupMsg msg, MsgSender msgsender, CQCodeUtil cqCodeUtil) {
		ApiportService service = SpringContextUtil.getBean(ApiportService.class);
		Apiport one = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
		if(one!=null) {
			if("部落阵型".equals(clansmsg)||"coc阵型".equals(clansmsg)||"COC阵型".equals(clansmsg)) {
				OpenLayout open = openlayout.getSuiji();
				String dldate = open.getDldate();
				if(dldate!=null) {
					long timedifference = TimeUtils.timedifference(dldate);
					if(timedifference>0) {
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), "[CQ:face,id=190] 编号："+open.getNumber()+"\n[CQ:emoji,id=127758]"+open.getDlurl()+"[CQ:image,file="+open.getImageUrl()+"]"+open.getRemark());
						return true;
					}
				}
				String url = DlCustom.dl(open.getUrl());
				open.setDlurl(url);
				open.setDldate(TimeUtils.endDdHhmmss());
				String re = "[CQ:face,id=190] 编号："+open.getNumber()+"\n[CQ:emoji,id=127758]"+url+"[CQ:image,file="+open.getImageUrl()+"]"+open.getRemark();
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), re);
				openlayout.updateById(open);
				return true;
			}else {
				List<OpenLayout> list = openlayout.query().eq("number", clansmsg).list();
				for (OpenLayout open : list) {
					String dldate = open.getDldate();
					if(dldate!=null) {
						long timedifference = TimeUtils.timedifference(dldate);
						if(timedifference>0) {
							msgsender.SENDER.sendGroupMsg(msg.getGroup(), "[CQ:face,id=190] 编号："+open.getNumber()+"\n[CQ:emoji,id=127758]"+open.getDlurl()+"[CQ:image,file="+open.getImageUrl()+"]"+open.getRemark());
							continue;
						}
					}
					String url = DlCustom.dl(open.getUrl());
					open.setDlurl(url);
					open.setDldate(TimeUtils.endDdHhmmss());
					String re = "[CQ:face,id=190] 编号："+open.getNumber()+"\n[CQ:emoji,id=127758]"+url+"[CQ:image,file="+open.getImageUrl()+"]"+open.getRemark();
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), re);
					openlayout.updateById(open);
					continue;
				}
				if(list.size()>0) {
					return true;
				}
			}
			return false;
		}
		return false;
	}
	/*****
	 * 代管人员操作
	 */
	public Boolean gradeAdministrotor(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender) {
		List<CQCode> CodeType = cqCodeUtil.getCQCodeFromMsgByType(msg.getMsg(), CQCodeTypes.at);
		String removeMsg = cqCodeUtil.removeCQCodeFromMsg(msg.getMsg(),CQCodeTypes.at);
		removeMsg = removeMsg.replaceAll(" ", "").replaceAll("	", "").replaceAll(",", "").replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", "");
		//处理禁言
		if(CodeType.size()>0&&(removeMsg.equals("禁言")||removeMsg.equals("解除禁言")||removeMsg.equals("取消禁言"))) 
		{
			GradeAdministrator one = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("prohibits", "1").one();
			GradeAdministrator ones = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("noprohibits", "1").one();
			if(one!=null||ones!=null) {
				for (CQCode cqCode : CodeType) {
					GradeAdministrator one2 = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("whitelist", "1").one();
					String string = cqCode.get("qq");
					if(one2!=null) {
						long max=2591999,min=600;
						long time = (long) (Math.random()*(max-min)+min);
						if(removeMsg.equals("解除禁言")||removeMsg.equals("取消禁言")) {
							time = (long)0;
						}
						msgsender.SETTER.setGroupBan(msg.getGroup(), string,time);
					}else {
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+string+"拥有免死金牌，咱动不得！");
					}
				}
			}
			return true;
		}
		//处理踢出
		if(CodeType.size()>0&&(removeMsg.equals("踢出")||removeMsg.equals("踢人")||removeMsg.equals("踢"))) 
		{
			GradeAdministrator one = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("kick", "1").one();
			if(one!=null) {
				for (CQCode cqCode : CodeType) {
					GradeAdministrator one2 = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("whitelist", "1").one();
					String string = cqCode.get("qq");
					if(one2!=null) {
						//踢出，允许重新加入
						msgsender.SETTER.setGroupMemberKick(msg.getGroup(), string, false);
					}else {
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+string+"拥有免死金牌，咱动不得！");
					}
				}
				return true;
			}
		}
		if(CodeType.size()>0&&(removeMsg.equals("拉黑"))) 
		{
			GradeAdministrator one = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("blacklist", "1").one();
			if(one!=null) {
				for (CQCode cqCode : CodeType) {
					GradeAdministrator one2 = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("whitelist", "1").one();
					String string = cqCode.get("qq");
					if(one2!=null) {
						//踢出，且不允许加入
						msgsender.SETTER.setGroupMemberKick(msg.getGroup(), string, true);
					}else {
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+string+"拥有免死金牌，咱动不得！");
					}
				}
				return true;
			}
		}
		return false;
	}
	/** 刷屏禁言 
	 * @param msg **/
	public Boolean spam(GroupMsg msg,MsgSender msgsender,CQCodeUtil cqCodeUtil) {
		GradeAdministrator one2 = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("whitelist", "1").one();
		//判断时代管的话，不予处理
		if(one2!=null||msg.getGroup().equals("1000000")) {
			return false;
		}
		SpamAdmin one = adminservice.query().eq("grouonumber", msg.getGroup()).eq("isgoto", "1").one();
		if(one!=null) {
			Spam spam = spanservice.query().eq("groupnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).one();
			if(spam!=null) {
				//判断字数是否大于X
				String msg2 = msg.getMsg();
				msg2 = cqCodeUtil.removeCQCodeFromMsg(msg2, CQCodeTypes.image);
				if(one.getMsglength()!=0&&msg2.length()>=one.getMsglength()) {
					if(one.getTime()>0) {
						msgsender.SETTER.setGroupBan(msg.getGroup(), msg.getQQ(), one.getTime() * 60);
					}
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+ "您发言的字数过长，影响其他用户聊天哦！");
					spam.setMsg("");
					spam.setData(TimeUtils.getStringDate());
					spam.setSum(1);
					spam.setDatasum(1);
					spanservice.updateById(spam);
					return true;
				}
				
				//比较和上一条的发言时间 返回的时 秒数
				long datadifference = TimeUtils.datadifference(spam.getData());
				if(datadifference!=-1&&one.getTimes()>0) {
					//如果发言间隔时间 <=  发言设置的间隔时间
					if(datadifference<=one.getTimes()) {
						//判断在刷屏
						if(msg.getMsg().equals(spam.getMsg())) {
							Integer sum = spam.getSum() + 1;
							Integer datasum = spam.getDatasum() + 1;
							if(sum >= one.getStatementsum()||datasum >= one.getMsgfrequency()) {
								//设置用户禁言
								if(one.getTime()>0) {
									msgsender.SETTER.setGroupBan(msg.getGroup(), msg.getQQ(), one.getTime() * 60);
								}
								msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+ "请不要刷屏哦！");
								spam.setMsg("");
								spam.setData(TimeUtils.getStringDate());
								spam.setSum(1);
								spam.setDatasum(1);
								spanservice.updateById(spam);
								return true;
							}else {
								spam.setMsg(msg.getMsg());
								spam.setSum(sum);
								spam.setDatasum(datasum);
								spam.setData(TimeUtils.getStringDate());
								spanservice.updateById(spam);
							}
						}else {
							Integer datasum = spam.getDatasum() + 1;
							if(datasum >= one.getMsgfrequency()) {
								//设置用户禁言
								if(one.getTime()>0) {
									msgsender.SETTER.setGroupBan(msg.getGroup(), msg.getQQ(), one.getTime() * 60);
								}
								msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+ "请不要刷屏哦！");
								spam.setMsg("");
								spam.setData(TimeUtils.getStringDate());
								spam.setSum(1);
								spam.setDatasum(1);
								spanservice.updateById(spam);
								return true;
							}else {
								spam.setMsg(msg.getMsg());
								spam.setDatasum(datasum);
								spam.setData(TimeUtils.getStringDate());
								spanservice.updateById(spam);
							}
						}
						
					}else {
						//正常发言
						spam.setMsg(msg.getMsg());
						spam.setData(TimeUtils.getStringDate());
						spam.setSum(1);
						spam.setDatasum(1);
						spanservice.updateById(spam);
					}
				}else {
					System.out.println("刷屏禁言:无效时间不予处理！");
				}
				
			}else {
				//保存此人聊天的情况
				Spam spamentity = new Spam();
				spamentity.setGroupnumber(msg.getGroup());
				spamentity.setQqnumber(msg.getQQ());
				spamentity.setSum(1);
				spamentity.setMsg(msg.getMsg());
				spamentity.setData(TimeUtils.getStringDate());
				spamentity.setDatasum(1);
				spanservice.save(spamentity);
			}
		}
		
		return false;
	}
	
	
	/*****
	 * 违禁词处理
	 * @param msg
	 * @param msgsender
	 */
	private Boolean LexiconIllegal(GroupMsg msg, MsgSender msgsender) {
		GradeAdministrator one2 = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("whitelist", "1").one();
		if(one2!=null) {
			return false;
		}
		int a = 0;
		//一.首先做模糊匹配
		List<LexiconIllegal> list = iservice.query().eq("qunnumber", msg.getGroup()).eq("type", "包含").eq("isuser", "1").list();
		for (LexiconIllegal lexiconIllegal : list) {
			if(msg.getMsg().indexOf(lexiconIllegal.getTextillegal())!=-1) {
				dispose(msg,lexiconIllegal,msgsender);
				a += 1;
			}
		}
		//二.做完全匹配模式
		List<LexiconIllegal> list2 = iservice.query().eq("qunnumber", msg.getGroup()).eq("type", "完全").eq("isuser", "1").eq("textillegal", msg.getMsg()).list();
		for (LexiconIllegal lexiconIllegal : list2) {
			dispose(msg,lexiconIllegal,msgsender);
		}
		if(list2.size()>0||a>0) {
			return true;
		}
		return false;
	}
	
	
	/****
	 * 发违禁词进行处理！惩罚！
	 * @param msg 
	 * @param lexiconIllegal
	 * @param msgsender
	 */
	private void dispose(GroupMsg msg, LexiconIllegal lexiconIllegal, MsgSender msgsender) {
		//1.首先处理违规人员
		switch (lexiconIllegal.getCode()) {
		case "禁言":
			Long time = (long)lexiconIllegal.getTime();
			msgsender.SETTER.setGroupBan(msg.getGroup(), msg.getQQ(), time * 60);
			break;
		case "踢出":
			msgsender.SETTER.setGroupMemberKick(msg.getGroup(), msg.getQQ(), false);
			break;
		case "撤回":
			SysUserService sysuserservice = SpringContextUtil.getBean(SysUserService.class);
			SysUser sys = sysuserservice.query().eq("username", msg.getGroup()).one();
			if(sys!=null&&sys.getAdministratoring()==true) {
				msgsender.SETTER.setMsgRecall(msg.getId());
			}
			break;
		default:
			break;
		}
		//2.私聊：通知群内代管其发生的情况
		if(lexiconIllegal.getIsgoto()) {
			List<GradeAdministrator> list = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("lexiconillegal", "1").list();
			for (GradeAdministrator g : list) {
				String tomsgisgoto ="时间："+TimeUtils.getTime() + "\n在群["+msg.getGroup()+"]中；\n用户["+msg.getQQ()+"]\n出现违规行为；\n原话：["+msg.getMsg()+"]\n处理方式:"+lexiconIllegal.getCode();
				msgsender.SENDER.sendPrivateMsg(g.getQqnumber(),tomsgisgoto);
			}
		}
	}
	
	
	/************      机器人应答         ***************/
	/****
	 * 机器人应答
	 * @param msg
	 * @param msgsender
	 */
	private Boolean lexicon(GroupMsg msg,CQCodeUtil cqCodeUtil, MsgSender msgsender) {
		String ms = msg.getMsg();
		/*if(cqCodeUtil.isAt(ms, BaseConfiguration.getLocalQQCode())) {
			//用户艾特出发事件
			ms = ms.replaceAll("[CQ:at,qq=822628363] ", "");
		}*/
		//一1.首先查询是否由多条选择一条的 完全匹配
		Lexicon Lexicon =  lsmapper.findByNumber(msg.getGroup(),ms);
		if(Lexicon!=null&&Lexicon.getAntistop()!=null&&Lexicon.getAntistop()!="") {
			if(Lexicon.getCode().equals("public")) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), GroupHtmlAndQqService.getMsghtml(Lexicon.getResponse(),cqCodeUtil,msg,msgsender));
			}else if(Lexicon.getCode().equals("private")) {
				msgsender.SENDER.sendPrivateMsg(msg.getQQ(), GroupHtmlAndQqService.getMsghtml(Lexicon.getResponse(),cqCodeUtil,msg,msgsender));
			}
			Lexicon.setSum(Lexicon.getSum()+1);
			lservice.updateById(Lexicon);
			grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
			return true;
		}
		//一2.做完全匹配模式
		List<Lexicon> list2 = lservice.query().eq("qunnumber", msg.getGroup()).eq("type", "完全").eq("isuser", "1").eq("antistop", ms).ne("number", "随机").list();
		for (Lexicon lexicon : list2) {
			if(lexicon.getCode().equals("public")) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), GroupHtmlAndQqService.getMsghtml(lexicon.getResponse(),cqCodeUtil,msg,msgsender));
			}else if(lexicon.getCode().equals("private")) {
				msgsender.SENDER.sendPrivateMsg(msg.getQQ(), GroupHtmlAndQqService.getMsghtml(lexicon.getResponse(),cqCodeUtil,msg,msgsender));
			}
			lexicon.setSum(lexicon.getSum()+1);
			lservice.updateById(lexicon);
			grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
		}
		if(list2.size()>0) {
			return true;
		}
		boolean re = false;
		
		//后期优化，因为数据库做不到这个效果
		//二1.模糊匹配。多条选择一条
		List<Lexicon> numberlexicon = lservice.query().eq("qunnumber", msg.getGroup()).eq("type", "模糊").eq("isuser", "1").eq("number", "随机").list();
		Collections.shuffle(numberlexicon);//打乱表的顺序
		for (Lexicon lexi : numberlexicon) {
			if(ms.indexOf(lexi.getAntistop())!=-1) {
				if(lexi.getCode().equals("public")) {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), GroupHtmlAndQqService.getMsghtml(lexi.getResponse(),cqCodeUtil,msg,msgsender));
				}else if(lexi.getCode().equals("private")) {
					msgsender.SENDER.sendPrivateMsg(msg.getQQ(), GroupHtmlAndQqService.getMsghtml(lexi.getResponse(),cqCodeUtil,msg,msgsender));
				}
				lexi.setSum(lexi.getSum()+1);
				lservice.updateById(lexi);
				grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
				return true;
			}
		}
		
		//二2.首先做模糊匹配
		List<Lexicon> list = lservice.query().eq("qunnumber", msg.getGroup()).eq("type", "模糊").eq("isuser", "1").ne("number", "随机").list();
		for (Lexicon lexicon : list) {
			if(ms.indexOf(lexicon.getAntistop())!=-1) {
				if(lexicon.getCode().equals("public")) {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), GroupHtmlAndQqService.getMsghtml(lexicon.getResponse(),cqCodeUtil,msg,msgsender));
				}else if(lexicon.getCode().equals("private")) {
					msgsender.SENDER.sendPrivateMsg(msg.getQQ(), GroupHtmlAndQqService.getMsghtml(lexicon.getResponse(),cqCodeUtil,msg,msgsender));
				}
				lexicon.setSum(lexicon.getSum()+1);
				lservice.updateById(lexicon);
				grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
				re = true;
			}
		}
		if(re) {
			return true;
		}
		return false;
	}
	
	
	
}
